﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DingChiServiceApp.db;
using DingChiServiceApp.helper;

namespace DingChiServiceApp
{
    public abstract class SqlServerDao<T> where T : BaseEntity, new()
    {
        private static DbHelper instance;

        public static DbHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new SqlServerHelper(GetConnString());
                }
                DbHelper.isDebug = true;
                DbHelper.enableErrorLog = true;
                return instance;
            }
        }

        private static string GetConnString()
        {
            LocalConfig localConfig = LocalConfigJsonDao.Instance.GetLocalConfig();

            var conn = ConnectionStringBuilder.GetConnectionString(localConfig.dataSource, localConfig.dbName, localConfig.userID, localConfig.pwd, localConfig.port);
            Console.WriteLine(conn);
            return conn;
        }

        public abstract string GetTableName();

        public int Insert(T entity)
        {
            string sql = SqlServerSqlBulider.GetInsertSql(entity,GetTableName(),DuplicateField.duplicate_id.ToString());
            return Instance.Insert(sql);
        }
        public int Delete(T entity)
        {
            return Instance.Delete(entity);
        }

        public int Delete(long id)
        {
            var obj = new T() { duplicateId = id };
            return Instance.Delete(obj);
        }

        public int Update(T entity)
        {
            string sql = SqlServerSqlBulider.GetUpdateSql(entity, GetTableName(), DuplicateField.duplicate_id.ToString());
            return Instance.Update(sql);
        }

        public int Clear()
        {
            string table = SqlBuilder.GetTableName(new T());
            string condition = "id > 0";
            string sql = SqlBuilder.GetDeleteSql(table, condition);
            return Instance.ExecuteNonQuery(sql);
        }

        public List<T> SelectAll()
        {
            string table = GetTableName();
            string sql = SqlBuilder.GetSelectSql(table);
            return Instance.Select<T>(sql);
        }

        public T FindById(long id)
        {            
            string tableName = GetTableName();
            string sql = $" select top 1 *   FROM {tableName} where id = {id};";
            List<T> datas = Instance.Select<T>(sql);
            return datas.Count > 0 ? datas[0] : null;
        }

    }
}
